import { intl } from '@/utils';
import { SettingOutlined } from '@ant-design/icons';
import { Button, Modal, Spin } from 'antd';
import SelectBox from 'devextreme-react/select-box';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import CpasLayout from '~/public/cpas-business/cpas-table/CpasLayout';
import AgeCalcButton, { getStartAandEndYear } from './components/AgeCalcButton';
import AgeConfigButton from './components/AgeConfigButton';
import { getInvAgeColumns } from './components/AgeConfigButton/service';
import { AgeContext } from './context/useAgeContext';
import { ColumnFields } from './fields';
import './index.less';
import {
  calcInvAge,
  calcInvAgeCheck,
  calcInvAgeStatus,
  getSubjectCategory,
  getSubjectInvList,
  stopInvAge,
} from './service';

const InventoryAgeAnalysis = (props: any) => {
  const pageType = props.params?.type;
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as API.CurPart;

  const ztModel = useModel('ztModel');

  const [startAndEndYear, setStartAndEndYear] = useState<any>({
    startYear: '',
    endYear: '',
  });
  const [accountYearData, setAccountYearData] = useState<any[]>([]);
  const [accountTreeList, setAccountTreeList] = useState<any[]>([]);
  const [statisticTypeData] = useState<any[]>([
    {
      displayName: '按汇总方式',
    },
    {
      displayName: '按批次方式',
    },
  ]);
  const [statisticType, setStatisticType] = useState<string>('按汇总方式');

  const MountedRef1 = useRef(false);
  const MountedRef2 = useRef(false);
  const [calcLoading, setCalcLoading] = useState<boolean>(false);
  const [progressInfo, setProgressInfo] = useState({
    progressValue: 0,
    progressText: '',
    elapsedTime: '',
  });

  const timerRef = useRef<any>();
  const cpasLayoutRef = useRef<any>();

  const DataTreeRef = useRef<any>();
  const accountYearRef = useRef<any>();
  const invAgeConfigRef = useRef<any>();
  const StatisticTypeRef = useRef<any>('按汇总方式');

  const [accountYear, setAccountYear] = useState<string>(ztModel.defaultValue);
  const [timeData, setTimeData] = useState<string>('');
  const [selDefaultValue, setSelDefaultValue] = useState<any>('');

  const treeData = useRef<any>([]);

  const [columnsData, setColumnsData] = useState<any[]>(ColumnFields);

  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: '8px',
  };
  const Titlestyle: React.CSSProperties = { marginRight: '8px' };

  const changeTimes = () => {
    setTimeData(`${new Date().getTime()}`);
  };

  useEffect(() => {
    ztModel.refresh();
  }, []);

  useEffect(() => {
    if (ztModel.defaultValue) {
      const DataId = ztModel.defaultValue;
      const dataList = ztModel.dataList;
      accountYearRef.current = DataId;
      setAccountYear(DataId);
      setAccountYearData(dataList);
      const { startYear, endYear } = getStartAandEndYear(dataList);
      setStartAndEndYear({ startYear, endYear });
    }
  }, [ztModel.defaultValue, ztModel.dataList]);

  const getInvAgeColumnsData = async () => {
    const res = await getInvAgeColumns({
      dbname,
    });
    let colTempData = ColumnFields;
    if (res.success) {
      if (Array.isArray(res.data) && res.data.length > 0) {
        const columns = res.data
          .filter((item) => item.isShow)
          .map((item: any) => {
            return {
              dataField: item.fieldName,
              caption: item.fieldTitle,
              dataType: 'number',
              alignment: 'right',
              format: '#,##0.00',
              allowEditing: false,
              width: 120,
            };
          });
        colTempData = colTempData.map((item: any) => {
          if (item.caption === '库龄') {
            item.columns = columns;
            return item;
          }
          return item;
        });
        if (StatisticTypeRef.current === '按汇总方式') {
          colTempData = colTempData.filter((item: any) => item.caption !== '批次');
        }
        setColumnsData(colTempData);
      }
    }
  };

  const resetProgressInfo = () => {
    setProgressInfo({
      progressValue: 0,
      progressText: '',
      elapsedTime: '',
    })
  }

  const clearTimer = () => {
    if (timerRef?.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  };

  const stop = async () => {
    await stopInvAge({ dbname, Data_ID: accountYear, statisticType });
  };

  const pollCalcStatus = () => {
    if (timerRef?.current) {
      clearInterval(timerRef.current);
    }
    const year = accountYear ? accountYear : accountYearRef.current;
    timerRef.current = setInterval(async () => {
      const res = await calcInvAgeStatus({
        dbname,
        Data_ID: year,
        statisticType,
      });
      if (res.success) {
        const data = res?.data;
        // const currYear = data?.year || '';
        if (data) {
          const progressInfoData = data.progressInfo || {};
          Modal.destroyAll();
          if (progressInfoData?.status === 'completed') {
            setCalcLoading(false);
            clearTimer();
            resetProgressInfo()
            // notify(`${accountYear}库龄计算成功`, 'success', 2000);
            Modal.success({
              centered: true,
              title: `提示`,
              content: `【${startAndEndYear.startYear}-${startAndEndYear.endYear}年度区间】【${statisticType}】 库龄计算成功`,
              onOk: () => {
                changeTimes();
                stop();
              },
            });
          }
          if (['success', 'pending'].includes(progressInfoData?.status)) {
            setCalcLoading(true);
            setProgressInfo({
              progressValue: progressInfoData?.progressValue,
              progressText: progressInfoData?.progressText,
              elapsedTime: progressInfoData?.elapsedTime,
            });
          }
          if (['error', 'failed'].includes(progressInfoData?.status)) {
            clearTimer();
            setCalcLoading(false);
            setProgressInfo({
              progressValue: progressInfoData?.progressValue,
              progressText: progressInfoData?.progressText,
              elapsedTime: progressInfoData?.elapsedTime,
            });
            Modal.error({
              centered: true,
              title: `提示`,
              content: `${progressInfoData?.progressText}`,
              onOk: () => {
                stop();
              },
            });
          }
        } else {
          // clearTimer();
        }
      }
    }, 1000);
  };

  const reCalcInvAge = async (type = statisticType, startEndYear = startAndEndYear) => {
    const { startYear, endYear } = startEndYear;
    if (startYear && endYear) {
      // 先停止之前的计算，重新开始计算
      await stop()
      setCalcLoading(false)
      clearTimer();
      resetProgressInfo()
      setCalcLoading(true);
      const params = {
        dbname,
        Data_ID: accountYear,
        statisticType: type,
        startYear,
        endYear,
      };
      await calcInvAge(params);
      pollCalcStatus();
    }
  };

  const onCalcOk = async (type = statisticType, startEndYear = startAndEndYear) => {
    await reCalcInvAge(type, startEndYear);
  };

  // 进入页面执行第一次按默认配置进行第一次计算
  const firstStartCalc = async (type: string, ref: any, startEndYear: any) => {
    if (startEndYear.startYear && startEndYear.endYear) {
      const res = await calcInvAgeCheck({
        dbname,
        Data_ID: accountYear,
        statisticType: type,
        startYear: startEndYear.startYear,
        endYear: startEndYear.endYear,
      });
      if (res.success) {
        const data = res?.data || [];
        if (data.length > 0) {
          ref.current = true;
        } else {
          // 开始第一次计算
          await reCalcInvAge(type, startEndYear);
        }
      }
    }
  };

  // 获取树数据
  const getSubjectCategoryDatas = async () => {
    const res = await getSubjectCategory({
      dbname,
    });
    if (res.success) {
      treeData.current = res.data;
      setAccountTreeList(res.data);
    }
  };

  const reloadTreeAndTable = async () => {
    getInvAgeColumnsData();
  };

  const onSelectionChangeds = (e: any) => {
    const v: any = window.localStorage.getItem(`selectDefaultTool_${dbname}`);
    let selectDefaultIDs = JSON.parse(v);
    selectDefaultIDs = { ...selectDefaultIDs, tabledataId: e.selectedItem.Data_ID };
    // 本地存储 持久化数据
    window.localStorage.setItem(`selectDefaultTool_${dbname}`, JSON.stringify(selectDefaultIDs));
    const selectedItem = e.selectedItem;
    setAccountYear(selectedItem.Data_ID);
  };

  const onSelectionChangedStatistic = async (e: any) => {
    setStatisticType(e.selectedItem.displayName);
    StatisticTypeRef.current = e.selectedItem.displayName;
    await getInvAgeColumnsData();
  };

  useEffect(() => {
    getSubjectCategoryDatas();
    getInvAgeColumnsData();
  }, []);

  useEffect(() => {
    if (!MountedRef1.current && statisticType) {
      // 检查是否计算过
      if (statisticType === '按汇总方式') {
        console.log(`🚀--Nice ~ InventoryAgeAnalysis ~ startAndEndYear:`, startAndEndYear)
        firstStartCalc(statisticType, MountedRef1, startAndEndYear);
      }
    }
  }, [statisticType, startAndEndYear, MountedRef1.current]);

  useEffect(() => {
    if (!MountedRef2.current && statisticType) {
      // 检查是否计算过
      if (statisticType === '按批次方式') {
        firstStartCalc(statisticType, MountedRef2, startAndEndYear);
      }
    }
  }, [statisticType, startAndEndYear, MountedRef2.current]);

  const [categoryId, setCategoryId] = useState('all');
  // 触发局部组件刷新
  const [refreshTime, setRefreshTime] = useState(new Date().getTime());

  const DataRef = useRef<any>();
  const devTreeRef = useRef<any>();

  // 分页
  const [totalCount, setTotalCount] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(50);
  const [devGuidData, setDevGuidData] = useState<any[]>([]);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);

  const getDevGridData = async (params: any) => {
    if (spinLoad) return;
    setSpinLoad(true);
    try {
      const res = await getSubjectInvList(params);
      if (res.success) {
        setDevGuidData(res.data);
      }
      setSpinLoad(false);
    } catch (error) {
      setSpinLoad(false);
    } finally {
      setSpinLoad(false);
    }
  };

  useEffect(() => {
    if (accountYear && statisticType) {
      const { startYear, endYear } = startAndEndYear;
      if (startYear && endYear) {
        const params = {
          dbname,
          Data_ID: accountYear,
          statisticType,
          categoryId: categoryId || 'all', // 默认选择全部
          startYear,
          endYear,
        };
        getDevGridData(params);
      }
    }
  }, [accountYear, statisticType, categoryId, refreshTime, timeData, startAndEndYear]);

  const selectItem = useCallback((e: any) => {
    const itemData = e.itemData;
    setCategoryId(itemData.id);
  }, []);

  const renderSearch = useCallback(() => {
    if (accountYearData.length === 0) return null;
    return (
      <div style={Divstyle}>
        <div style={Divstyle}>
          <div style={Titlestyle}>{intl('report.subject.account', '账套:')}</div>
          <SelectBox
            width={240}
            dataSource={accountYearData}
            displayExpr="displayName"
            valueExpr="Data_ID"
            defaultValue={accountYear}
            onSelectionChanged={onSelectionChangeds}
            dropDownOptions={{
              width: '350px',
            }}
          />
        </div>
        <div style={Divstyle}>
          <div style={Titlestyle}>统计方式:</div>
          <SelectBox
            width={120}
            items={statisticTypeData}
            displayExpr="displayName"
            valueExpr="displayName"
            value={statisticType}
            defaultValue="按汇总方式"
            onSelectionChanged={onSelectionChangedStatistic}
          />
        </div>
        <AgeCalcButton
          dbname={dbname}
          accountYear={accountYear ? accountYear : accountYearRef.current}
          statisticType={statisticType}
          calcLoading={calcLoading}
          accountYearData={accountYearData}
          progressInfo={progressInfo}
          startAndEndYear={startAndEndYear}
          onOK={() => {
            onCalcOk();
          }}
        />
        <Button
          style={{
            marginLeft: '8px',
          }}
          type="primary"
          size="middle"
          className="invAge-setting-btn"
          icon={<SettingOutlined />}
          onClick={() => {
            invAgeConfigRef.current.showPupop();
          }}
        >
          设置库龄段
        </Button>
      </div>
    );
  }, [accountYearData, statisticType, calcLoading, accountYear, startAndEndYear, progressInfo]);
  const contextValue = {
    dbname,
    accountYear,
    statisticType,
  };

  return (
    <AgeContext.Provider value={contextValue}>
      <div
        className="invAge-container"
        style={{
          border: '0px solid green',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        {useMemo(() => {
          return (
            <>
              {spinLoad && <Spin spinning={spinLoad} className="layout-spin" />}
              <CpasLayout
                id="invAge"
                ref={cpasLayoutRef}
                pageType={'存货库龄分析'}
                treeListData={accountTreeList}
                tableColumnsData={columnsData}
                // tableData={[]}
                tableData={devGuidData}
                renderSearch={renderSearch}
                isLeftTree={true}
                isJumpRowDetail={false}
                treeClickCallback={selectItem}
                disabledHomeIcon={true}
                disableGridSummary={false}
                refreshBtnCallback={() => {
                  changeTimes();
                }}
              />
            </>
          );
        }, [accountTreeList, columnsData, devGuidData, renderSearch, spinLoad])}
        {/* 库龄设置 */}
        <AgeConfigButton
          ref={invAgeConfigRef}
          reloadDevTable={() => {
            reloadTreeAndTable();
          }}
        />
      </div>
    </AgeContext.Provider>
  );
};

export default InventoryAgeAnalysis;
